//
//  JobDetailsViewController.m
//  intelligent
//
//  Created by Ace Portgas on 2024/2/19.
//

#import "JobDetailsViewController.h"
#import "VIPView.h"
#import "MeVipViewController.h"
#import "ScoreView.h"
#import "FankuiViewController.h"
@interface JobDetailsViewController ()<UITextViewDelegate>
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) UITextView *questionTextView;
@property (strong, nonatomic) UIButton * createAnswerBtn;
@property (strong, nonatomic) UIButton *answerBtn;
@property (strong, nonatomic) UIButton *collectionBtn;
@property (strong, nonatomic) UIButton *textCopyBtn;
@property (strong, nonatomic) UILabel * numberLabel;
@property (assign,nonatomic) CGFloat defaultContentH;
@property (strong,nonatomic) UIButton * reloadAnswerBtn;
@property (strong,nonatomic) UIActivityIndicatorView *activityIndicator;
@property (strong,nonatomic) NSString * answerID;
@property (strong,nonatomic) NSString * answerString;
@property (nonatomic,strong) NSMutableArray * receivedStrings;
@property (nonatomic,assign)BOOL startPrint;
@property (nonatomic,strong)NSTimer * timer;
@end

@implementation JobDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = SQNSLocalString(@"工作页");
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    tapGesture.cancelsTouchesInView = NO; // 这个设置可选，确保点击不会影响其他视图的触摸事件
    [self.view addGestureRecognizer:tapGesture];
    _receivedStrings = [NSMutableArray array];
}

- (void)dismissKeyboard {
    [self.view endEditing:YES];
}

-(void)SQ_UIViewForSelfView{
    CGFloat defaultWidth = SCREEN_WIDETH - 24;
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    _scrollView.bounces = NO;
    [self.view addSubview:_scrollView];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.zx_navBar.mas_bottom).offset(12);
        make.left.mas_equalTo(self.view).offset(12);
        make.right.mas_equalTo(self.view).offset(-12);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-11 - 48 - 10);
    }];
    
    CGFloat questionTextX = 0;
    CGFloat questionTextY = 0;
    CGFloat questionTextW = defaultWidth;
    CGFloat questionTextH = 200;
    _questionTextView = [[UITextView alloc] init];
    _questionTextView.frame = CGRectMake(0,0,defaultWidth,200);
    _questionTextView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1.0];
    _questionTextView.layer.cornerRadius = 16;
    _questionTextView.delegate = self;
    _questionTextView.text = _placeholder;
    _questionTextView.textColor = [UIColor colorWithHexString:@"#333333"];
    _questionTextView.font = [UIFont systemFontOfSize:14];
    _questionTextView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [_scrollView addSubview:_questionTextView];
    
    CGFloat createAnswerW = defaultWidth - 48;
    CGFloat createAnswerH = 40;
    CGFloat createAnswerX = 24;
    CGFloat createAnswerY = questionTextH - createAnswerH / 2;
    _createAnswerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _createAnswerBtn.frame = CGRectMake(createAnswerX, createAnswerY, createAnswerW, createAnswerH);
    [_scrollView addSubview:_createAnswerBtn];
    // gradient
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = _createAnswerBtn.bounds;
    gl.startPoint = CGPointMake(0, 0.5);
    gl.endPoint = CGPointMake(1, 0.5);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:117/255.0 green:248/255.0 blue:183/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:117/255.0 green:248/255.0 blue:240/255.0 alpha:1.0].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    _createAnswerBtn.layer.cornerRadius = 20;
    [_createAnswerBtn.layer addSublayer:gl];
    _createAnswerBtn.layer.masksToBounds = YES;
    _createAnswerBtn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    [_createAnswerBtn addTarget:self action:@selector(startCreateAnswer) forControlEvents:UIControlEventTouchUpInside];
    [_createAnswerBtn setTitle:SQNSLocalString(@"开始生成") forState:UIControlStateNormal];
    [_createAnswerBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    // 创建一个活动指示器
    _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium]; // 选择样式，此处为白色大菊花
    _activityIndicator.size = CGSizeMake(30, 30);
    _activityIndicator.center = CGPointMake(_createAnswerBtn.bounds.size.width / 2.0, _createAnswerBtn.bounds.size.height / 2.0); // 设置中心点，使其居中
    _activityIndicator.hidesWhenStopped = YES; // 不显示时隐藏
    _activityIndicator.color = [UIColor colorWithHexString:@"#333333"];
    // 将活动指示器添加到UIButton上
    [_createAnswerBtn addSubview:_activityIndicator];

    
    CGFloat numberLabelX = 0;
    CGFloat numberLabelY = createAnswerY + createAnswerH + 18;
    CGFloat numberLabelW = 200;
    CGFloat numberLabelH = 22;
    _numberLabel = [[UILabel alloc] init];
    _numberLabel.frame = CGRectMake(numberLabelX,numberLabelY,numberLabelW,numberLabelH);
    _numberLabel.numberOfLines = 0;
    _numberLabel.textAlignment = NSTextAlignmentLeft;
    _numberLabel.font = [UIFont systemFontOfSize:16];
    _numberLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    _numberLabel.text = [NSString stringWithFormat:@"%@：0",SQNSLocalString(@"字数")];
    _numberLabel.hidden = YES;
    [_scrollView addSubview:_numberLabel];

    CGFloat collectionBtnW = 24;
    CGFloat collectionBtnH = collectionBtnW;
    CGFloat collectionBtnX = defaultWidth - 24 - 8;
    CGFloat collectionBtnY = createAnswerY + createAnswerH + 16;
    _collectionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _collectionBtn.frame = CGRectMake(collectionBtnX, collectionBtnY, collectionBtnW, collectionBtnH);
    [_collectionBtn setImage:SQGetImage(@"收藏-灰") forState:UIControlStateNormal];
    [_collectionBtn setImage:SQGetImage(@"收藏-亮") forState:UIControlStateSelected];
    [_collectionBtn addTarget:self action:@selector(collectionCurrentAnswer) forControlEvents:UIControlEventTouchUpInside];
    _collectionBtn.hidden = YES;
    [_scrollView addSubview:_collectionBtn];
    
    CGFloat copyBtnW = collectionBtnW;
    CGFloat copyBtnH = copyBtnW;
    CGFloat copyBtnX = collectionBtnX - copyBtnW - 8;
    CGFloat copyBtnY = collectionBtnY;
    _textCopyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _textCopyBtn.frame = CGRectMake(copyBtnX, copyBtnY, copyBtnW, copyBtnH);
    [_textCopyBtn setImage:SQGetImage(@"复制") forState:UIControlStateNormal];
    [_textCopyBtn addTarget:self action:@selector(copyAnswer) forControlEvents:UIControlEventTouchUpInside];
    _textCopyBtn.hidden = YES;
    [_scrollView addSubview:_textCopyBtn];
    
    CGFloat answerBtnX = 0;
    CGFloat answerBtnY = copyBtnY + copyBtnH + 12;
    CGFloat answerBtnW = defaultWidth;
    CGFloat answerBtnH = 68;
    _defaultContentH = answerBtnY + 48;
    _answerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _answerBtn.frame = CGRectMake(answerBtnX, answerBtnY, answerBtnW, answerBtnH);
    _answerBtn.backgroundColor = [UIColor colorWithHexString:@"#F4F4F4"];
    [_answerBtn setTitle:SQNSLocalString(@"这里将会展示生成的结果") forState:UIControlStateNormal];
    [_answerBtn setTitleColor:[UIColor colorWithHexString:@"333333"] forState:UIControlStateNormal];
    _answerBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _answerBtn.layer.cornerRadius = 16;
    _answerBtn.contentEdgeInsets = UIEdgeInsetsMake(24, 20, 24, 20);
    _answerBtn.titleLabel.numberOfLines = 0;
    _answerBtn.titleLabel.textAlignment = NSTextAlignmentLeft;// 设置按钮标题靠左对齐
    _answerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; // 水平居左
    _answerBtn.hidden = YES;
    [self.scrollView addSubview:_answerBtn];
    self.scrollView.contentSize = CGSizeMake(0, _defaultContentH + 20);
    
    CGFloat reloadAsnswerBtnW = SCREEN_WIDETH - 44;
    CGFloat reloadAsnswerBtnH = 48;
    CGFloat reloadAsnswerBtnX = 22;
    CGFloat reloadAsnswerBtnY = SCREEN_HEIGHT - ZXSafeAreaBottom - 11 - reloadAsnswerBtnH;
    _reloadAnswerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _reloadAnswerBtn.frame = CGRectMake(reloadAsnswerBtnX, reloadAsnswerBtnY, reloadAsnswerBtnW, reloadAsnswerBtnH);
    _reloadAnswerBtn.backgroundColor = [UIColor colorWithHexString:@"#333333"];
    [_reloadAnswerBtn setTitle:SQNSLocalString(@"重新生成") forState:UIControlStateNormal];
    [_reloadAnswerBtn setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
    _reloadAnswerBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    _reloadAnswerBtn.layer.cornerRadius = 16;
    [_reloadAnswerBtn addTarget:self action:@selector(startCreateAnswer) forControlEvents:UIControlEventTouchUpInside];
    _reloadAnswerBtn.hidden = YES;
    [self.view addSubview:_reloadAnswerBtn];
}

- (void)startCreateAnswer {
    // 开始菊花旋转
    [self.view endEditing:YES];
    self.scrollView.contentSize = CGSizeMake(0, self.defaultContentH + 20);
    self.scrollView.contentOffset = CGPointMake(0, 0);
    if (![UserModel share].isVip) {
        UserModel * mo = [UserModel share];
        if (mo.freeCount.integerValue == 0) {
            [self pushVIPAlert];
            return;
        }
        NSInteger count = mo.freeCount.integerValue - 1;
        if (count <=0) {
            count = 0;
        }
        mo.freeCount = [NSString stringWithFormat:@"%ld",count];
        [UserModel updateLocalUserModel:mo];
    }
    self.answerBtn.hidden = YES;
    self.collectionBtn.hidden = YES;
    self.textCopyBtn.hidden = YES;
    self.numberLabel.hidden = YES;
    self.reloadAnswerBtn.hidden = YES;
    [_activityIndicator startAnimating];
    [_createAnswerBtn setTitle:@"" forState:UIControlStateNormal];

    [YJProgressHUD SQ_showMsgWithoutView:SQNSLocalString(@"请耐心等待")];
    NSDictionary * dic = @{
        @"content":self.questionTextView.text,
        @"worksId":self.worksId
    };
    WS(weakSelf);
    [HttpTool post:CZWT paramDic:[NSMutableDictionary dictionaryWithDictionary:dic] successBlock:^(BaseModel * _Nonnull httpModel) {
//        if (weakSelf.startPrint == NO) {
            weakSelf.answerID = httpModel.data[@"id"];
            [weakSelf.answerBtn setTitle:@"" forState:UIControlStateNormal];
            [weakSelf.activityIndicator stopAnimating];
            [weakSelf.createAnswerBtn setTitle:SQNSLocalString(@"开始生成") forState:UIControlStateNormal];
            weakSelf.answerBtn.hidden = NO;
            weakSelf.collectionBtn.hidden = NO;
            weakSelf.textCopyBtn.hidden = NO;
            weakSelf.numberLabel.hidden = NO;
            weakSelf.reloadAnswerBtn.hidden = NO;
            weakSelf.startPrint = YES;
            [weakSelf.receivedStrings removeAllObjects];
            NSDictionary * dic = httpModel.data;
            NSString * text = dic[@"content"];
            weakSelf.numberLabel.text = [NSString stringWithFormat:@"%@：%lu",SQNSLocalString(@"字数"),(unsigned long)text.length];
        [weakSelf.answerBtn setTitle:text forState:UIControlStateNormal];
        if ([ScoreView SQ_ShowScoreViewWithClass:@"jobFirstQuestion"]) {
            [self pushScoreView];
        }
        CGSize titleSize = [text getSizeWithMaxSize:CGSizeMake(SCREEN_WIDETH - 24 - 40, MAXFLOAT) andFont:[UIFont systemFontOfSize:14]];
        weakSelf.answerBtn.frame = CGRectMake(weakSelf.answerBtn.frame.origin.x, weakSelf.answerBtn.frame.origin.y, weakSelf.answerBtn.frame.size.width, titleSize.height + 48);
        weakSelf.scrollView.contentSize = CGSizeMake(0, weakSelf.defaultContentH + titleSize.height);
//            for (NSUInteger i = 0; i < [text length]; i++) {
//                unichar character = [text characterAtIndex:i];
//                NSString *characterString = [NSString stringWithCharacters:&character length:1];
//                [weakSelf.receivedStrings addObject:characterString];
//            }
//            [weakSelf startPrintText];
//        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [weakSelf.activityIndicator stopAnimating];
        [weakSelf.createAnswerBtn setTitle:SQNSLocalString(@"开始生成") forState:UIControlStateNormal];
        [YJProgressHUD showMsgWithoutView:httpModel.message];
        
    }];
}

-(void)pushScoreView{
    ScoreView  * view = [[ScoreView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    LSTPopView * pop = [LSTPopView initWithCustomView:view
                                           parentView:nil
                                             popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleCenter;
    [pop pop];
    LSTPopViewWK(pop)
    [pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
    WS(weakSelf);
    [view setClickCancelBtnBlock:^{
        [wk_pop dismiss];
    }];
    [view setClickConfireBtnBlock:^{
        [wk_pop dismiss];
        [SKStoreReviewController requestReview];
    }];
    [view setClickFeedbackBtnBlock:^{
        [wk_pop dismiss];
        FankuiViewController *vc = [[FankuiViewController alloc]init];
        [self SQ_pushViewControllerFull:vc];
    }];
}

-(void)startPrintText{
    // 定义一个计数器
    __block NSInteger currentIndex = 0;
    WS(weakSelf);
    NSTimeInterval delay = 0.05; // 每个字符显示的时间间隔
    // 定义一个定时器，每隔0.03秒执行一次
    weakSelf.answerString = @"";
    self.timer = [NSTimer scheduledTimerWithTimeInterval:delay repeats:YES block:^(NSTimer * _Nonnull timer) {
        // 在主队列中执行更新 UI 的操作
        dispatch_async(dispatch_get_main_queue(), ^{
            // 判断是否已经拼接完所有的字符串
            if (currentIndex < weakSelf.receivedStrings.count) {
                @autoreleasepool {
                    // 获取当前需要拼接的字符串
                    NSString *stringToAppend = weakSelf.receivedStrings[currentIndex];
                    weakSelf.answerString = [NSString stringWithFormat:@"%@%@",weakSelf.answerString,stringToAppend];
                    [weakSelf.answerBtn setTitle:weakSelf.answerString forState:UIControlStateNormal];
                    CGSize titleSize = [weakSelf.answerBtn.titleLabel.text getSizeWithMaxSize:CGSizeMake(SCREEN_WIDETH - 24 - 40, MAXFLOAT) andFont:[UIFont systemFontOfSize:14]];
                    weakSelf.answerBtn.frame = CGRectMake(weakSelf.answerBtn.frame.origin.x, weakSelf.answerBtn.frame.origin.y, weakSelf.answerBtn.frame.size.width, titleSize.height + 48);
                    weakSelf.scrollView.contentSize = CGSizeMake(0, weakSelf.defaultContentH + titleSize.height);
                }
                currentIndex++;
            } else {
                weakSelf.startPrint = NO;
                [weakSelf.receivedStrings removeAllObjects];
                [weakSelf.timer invalidate];
                weakSelf.timer = nil;
                if ([ScoreView SQ_ShowScoreView]) {
                    [self pushScoreView];
                }
             
            }
        });
    }];
}

-(void)pushVIPAlert{
    if (![UserModel share].isVip) {
        VipView * view = [[VipView alloc]init];
        view.frame = CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT);
        LSTPopView * pop = [LSTPopView initWithCustomView:view
                                               parentView:nil
                                                 popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
        pop.hemStyle = LSTHemStyleCenter;
        [pop pop];
        LSTPopViewWK(pop)
        [pop setBgClickBlock:^{
            [wk_pop dismiss];
        }];
        WS(weakSelf);
        [view setOpenVIPBlock:^{
            [wk_pop dismiss];
            MeVipViewController  * vc = [[MeVipViewController alloc]init];
            [[Manager SQ_getCurrentViewController].navigationController pushViewController:vc animated:YES];
        }];
        [view setCloseViewBlock:^{
            [wk_pop dismiss];
        }];
    }
}


- (void)collectionCurrentAnswer {
    if (![_collectionBtn.titleLabel.text isEqualToString:_placeholder] && self.answerID) {
        self.collectionBtn.selected = !self.collectionBtn.selected;
            NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject:self.answerID forKey:@"id"];
            if (self.collectionBtn.selected) {
                [dic setObject:@"1" forKey:@"type"];
            } else {
                [dic setObject:@"0" forKey:@"type"];
            }
            [HttpTool post:@"chat/collect" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
                if (self.collectionBtn.selected) {
                    [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"收藏成功，个人中心收藏中查看")];
                }
            } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }];
    }
    if (self.collectionBtn.selected == YES) {
        
    }

}

-(void)copyAnswer{
    UIPasteboard *pab = [UIPasteboard generalPasteboard];
    pab.string = _answerBtn.titleLabel.text;
    if (pab == nil) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"复制失败")];
    } else {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"复制成功")];
    }
}

// 实现代理方法
- (void)textViewDidBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:_placeholder]) {
        textView.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@""]) {
        textView.text = _placeholder;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@""] && range.location == 0 && range.length == textView.text.length) {
        textView.text = _placeholder;
        return NO;
    }
    if ([textView.text isEqualToString:_placeholder]) {
        textView.text = @"";
    }
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
